package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"studios/models"
	"studios/util"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	var user models.User
	key := "count-" + username
	Count, _ := models.Rdb.Get(key).Result()
	if Count >= "3" {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "密码错误超过三次，2小时内不可登录",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	err := models.DB.Model(&models.User{}).Where("username = ?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "用户名不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if user.Password == util.Md5Pwd(password) {
		models.Rdb.Del(key)
		c.Data["json"] = JsonMsg{
			Code: 200,
			Msg:  "登录成功",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		models.Rdb.Incr(key)
		models.Rdb.Expire(key, time.Hour*2)
		c.Data["json"] = JsonMsg{
			Code: 500,
			Msg:  "密码错误",
			Data: nil,
		}
		c.ServeJSON()
	}
}
